<?php

App::uses('AppModel', 'Model');

/**
 * City Model
 *
 */
class City extends AppModel {
	
	public $name = "City";
	
	/**
	 * Use table
	 *
	 * @var mixed False or table name
	 */
	public $useTable = 'cities';
	
	/**
	 * Display field
	 *
	 * @var string
	 */
	public $displayField = 'name';
	
	/**
	 * Virtual fields
	 * @var array
	 */
	public $virtualFields = array (
		'latitude'  => 'X(City.position)',
		'longitude' => 'Y(City.position)'
	);
	
	
	/**
	 * Validation rules
	 *
	 * @var array
	 */
	public $validate = array(
		'name' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);
	
	public function beforeSave($options = array()) {
		// Convert latitude & longitude into POINT (position)
		if( isset($this->data[$this->name]['latitude']) && isset($this->data[$this->name]['longitude']) ) {
			$this->data[$this->name]['position']= DboSource::expression(sprintf('GeomFromText("POINT(%f %f)")',
				$this->data[$this->name]['latitude'],
				$this->data[$this->name]['longitude']
			));	
		}
		return true;	
	}
	
}
